package com.example.test_witns.ui.view_pages_home;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowInsets;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.NavOptions;
import androidx.navigation.fragment.NavHostFragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.test_witns.R;
import com.example.test_witns.adapter.blog.BlogAdapter;
import com.example.test_witns.databinding.FragmentViewPageHotBinding;
import com.example.test_witns.pojo.BannerDataInfo;
import com.example.test_witns.pojo.Blog;
import com.example.test_witns.pojo.BlogCover;
import com.example.test_witns.pojo.BlogResponse;
import com.example.test_witns.ui.blog_content.BlogContentActivity;
import com.example.test_witns.ui.login.LoginActivity;
import com.example.test_witns.utils.MyInfosHelper;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.youth.banner.Banner;
import com.youth.banner.adapter.BannerImageAdapter;
import com.youth.banner.holder.BannerImageHolder;
import com.youth.banner.indicator.CircleIndicator;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.GET;
import retrofit2.http.Query;

public class ViewPageHotFragment extends Fragment {
    private FragmentViewPageHotBinding binding;
    private Banner banner;
    private List<BlogCover> blogCoverList;
    private BlogAdapter blogAdapter;
    private RecyclerView blog_recycler;
    private List<BannerDataInfo> bannerDataInfos = new ArrayList<>();
    private static boolean ifBannerInitialed = false;
    public interface BlogApiService{
        @GET("getBlogs")
        Call<BlogResponse> getBlogs(@Query("num") long num);
    }

    public interface LoadBlogsCallback{
        void OnSuccess(int loadedBlogNum);
    }

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentViewPageHotBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        MyInfosHelper myInfosHelper = new MyInfosHelper(getContext());

        blog_recycler = root.findViewById(R.id.blog_recycler);
        blog_recycler.setLayoutManager(new LinearLayoutManager(getContext()));

        blogCoverList = new ArrayList<>();
        blogAdapter = new BlogAdapter(blogCoverList);
        blogAdapter.setOnBlogCoverClickListener(new BlogAdapter.OnBlogCoverClickListener() {
            @Override
            public void onBlogCoverClicked(long blogID, String authorName, String authorAvatarURL, String mainTitle, String subTitle,
                                           String introductionImageURL, String publishTime, String content, Integer likes_num, Integer stars_num,
                                           Integer comments_num, String blogContentImageURLs) {
                Intent intent = new Intent(getContext(), BlogContentActivity.class);
                intent.putExtra("mainTitle", mainTitle);
                intent.putExtra("subTitle", subTitle);
                intent.putExtra("authorAvatarURL", authorAvatarURL);
                intent.putExtra("introductionImageURL", introductionImageURL);
                intent.putExtra("publishTime", publishTime);
                intent.putExtra("authorName", authorName);
                intent.putExtra("content", content);
                intent.putExtra("blogID", blogID);
                intent.putExtra("likes_num", likes_num);
                intent.putExtra("stars_num", stars_num);
                intent.putExtra("comments_num", comments_num);
                intent.putExtra("blogContentImageURLs", blogContentImageURLs);
                startActivity(intent);
            }
        });
        blogAdapter.setOnMoreClickListener(new BlogAdapter.OnMoreClickListener() {
            @Override
            public void onMoreClicked() {
                BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(getContext());
                View view = getLayoutInflater().inflate(R.layout.custom_blog_cover_bottom_sheet_layout, null);

                bottomSheetDialog.setContentView(view);
                bottomSheetDialog.show();

                TextView custom_bottom_sheet_cancel = view.findViewById(R.id.custom_bottom_sheet_cancel);
                custom_bottom_sheet_cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        bottomSheetDialog.hide();
                    }
                });
            }
        });
        NavController navController = NavHostFragment.findNavController(this);
        blogAdapter.setOnViewContentWhenHaveNotLoginListener(new BlogAdapter.OnViewContentWhenHaveNotLoginListener() {
            @Override
            public void onViewContentWhenHaveNotLogin() {
                toast_Prohibited_Style("您尚未登录, 请登录");
                Intent intent = new Intent(getContext(), LoginActivity.class);
                startActivity(intent);
            }
        });
        blog_recycler.setAdapter(blogAdapter);
        blog_recycler.setNestedScrollingEnabled(false);

        LoadBlogs(new LoadBlogsCallback() {
            @Override
            public void OnSuccess(int loadedBlogNum) {

            }
        });

        SwipeRefreshLayout swipeRefreshLayout = root.findViewById(R.id.swipeRefreshLayout_home);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        blogAdapter.removeAllBlogCover();
                        LoadBlogs(new LoadBlogsCallback() {
                            @Override
                            public void OnSuccess(int loadedBlogNum) {

                            }
                        });
                    }
                }).start();
            }
        });

        if (!ifBannerInitialed){
            initBanner(bannerDataInfos, banner, root);
            ifBannerInitialed = true;
        }else {
            banner = root.findViewById(R.id.view_banner1);
            if (bannerDataInfos.isEmpty()){
                initBanner(bannerDataInfos, banner, root);
            }
            banner.setAdapter(new BannerImageAdapter<BannerDataInfo>(bannerDataInfos) {

                @Override
                public void onBindView(BannerImageHolder holder, BannerDataInfo data, int position, int size) {
                    holder.imageView.setImageResource(data.getImg());
                }
            }).addBannerLifecycleObserver(this)
                    .setIndicator(new CircleIndicator(getContext()));

            banner.setBannerGalleryEffect(10,15);

            banner.setOnBannerListener(new OnBannerListener<BannerDataInfo>() {

                @Override
                public void OnBannerClick(BannerDataInfo data, int position) {
                    switch (position){
                        case 0:
                            Toast.makeText(getContext(), "0", Toast.LENGTH_SHORT).show();
                            break;
                        case 1:
                            Toast.makeText(getContext(), "1", Toast.LENGTH_SHORT).show();
                            break;
                        case 2:
                            Toast.makeText(getContext(), "2", Toast.LENGTH_SHORT).show();
                            break;
                        case 3:
                            Toast.makeText(getContext(), "3", Toast.LENGTH_SHORT).show();
                            break;
                        default:Toast.makeText(getContext(), "default", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }

        NavOptions navOptions = new NavOptions.Builder()
                .setLaunchSingleTop(false) // 确保如果目标 Fragment 已经在顶部，不会创建新的实例
                .setPopUpTo(R.id.navigation_home, true) // 设置为 true 将移除直到起始目的地的所有 Fragment
                .setRestoreState(false) // 不恢复状态，通常与 setPopUpTo 结合使用
                .build();

        return root;
    }

    @NonNull
    private Banner initBanner(@NonNull List<BannerDataInfo> bannerDataInfos, Banner banner, View root){
        banner = (Banner) root.findViewById(R.id.view_banner1);

        bannerDataInfos.add(new BannerDataInfo(R.drawable.tesla_bot_ps_fixed,"title1"));
        bannerDataInfos.add(new BannerDataInfo(R.drawable.space_ship_ps_fixed,"title2"));
        bannerDataInfos.add(new BannerDataInfo(R.drawable.rust_ps_fixed,"title3"));
        bannerDataInfos.add(new BannerDataInfo(R.drawable.cyber_ghost_grils,"title4"));

        banner.setAdapter(new BannerImageAdapter<BannerDataInfo>(bannerDataInfos) {

                    @Override
                    public void onBindView(BannerImageHolder holder, BannerDataInfo data, int position, int size) {
                        holder.imageView.setImageResource(data.getImg());
                    }
                }).addBannerLifecycleObserver(this)
                .setIndicator(new CircleIndicator(getContext()));

        banner.setBannerGalleryEffect(10,15);

        banner.setOnBannerListener(new OnBannerListener<BannerDataInfo>() {

            @Override
            public void OnBannerClick(BannerDataInfo data, int position) {
                switch (position){
                    case 0:
                        Toast.makeText(getContext(), "0", Toast.LENGTH_SHORT).show();
                        break;
                    case 1:
                        Toast.makeText(getContext(), "1", Toast.LENGTH_SHORT).show();
                        break;
                    case 2:
                        Toast.makeText(getContext(), "2", Toast.LENGTH_SHORT).show();
                        break;
                    case 3:
                        Toast.makeText(getContext(), "3", Toast.LENGTH_SHORT).show();
                        break;
                    default:Toast.makeText(getContext(), "default", Toast.LENGTH_SHORT).show();
                }
            }
        });
        banner.setLoopTime(5000);

        return banner;
    }

    public void LoadBlogs(ViewPageHotFragment.LoadBlogsCallback loadBlogsCallback){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://" + "101.35.251.218" + ":8080/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        ViewPageHotFragment.BlogApiService blogApiService = retrofit.create(ViewPageHotFragment.BlogApiService.class);
        Call<BlogResponse> call = blogApiService.getBlogs(10);
        call.enqueue(new Callback<BlogResponse>() {

            @Override
            public void onResponse(Call<BlogResponse> call, Response<BlogResponse> response) {
                if (response.isSuccessful() && response.body() != null) {
                    BlogResponse blogResponse = response.body();
                    // 打印返回的数据类
                    Log.d("RetrofitResponse", blogResponse.toString());

                    int loadedBlogNum = 0;

                    // 处理每个博客条目
                    for (Blog blog : blogResponse.getData()) {
                        Log.d("Blog", blog.toString());
                        blogAdapter.addBlogCover(new BlogCover(blog.getBlog_ID(),
                                blog.getOwner_Avatar_URL(),
                                blog.getMain_title(),
                                blog.getSubtitle(),
                                "https://fftechuseravater.oss-cn-beijing.aliyuncs.com/images/blogCoverImages/" + blog.getCover_Image_URL(),
                                null,
                                blog.getOwner(),
                                blog.getStars_num(),
                                blog.getLikes_num(),
                                blog.getComments_num(),
                                blog.getPublish_Time(),
                                blog.getContent(),
                                blog.getContent_Images_URL()));

                        if(blog.getMain_title() != null){
                            loadedBlogNum++;
                        }
                    }
                    loadBlogsCallback.OnSuccess(loadedBlogNum);
                } else {
                    // 请求成功但返回的数据为空或状态码不是 200
                    Log.e("RetrofitError", "Response is not successful or body is null");
                }
            }

            /**
             * @param call
             * @param t
             */
            @Override
            public void onFailure(Call<BlogResponse> call, Throwable t) {
                showProhibitedStyleToastAboveView(blog_recycler, getContext(), "服务器连通性异常, 请检查网络");
            }
        });
    }

    public void showToastAboveView(View view, Context context, String message) {
        // 创建Toast
        View customView = LayoutInflater.from(context).inflate(R.layout.custom_toast_confirm_layout, null);
        TextView toastText = customView.findViewById(R.id.toast_message);
        toastText.setText(message);

        Toast toast = new Toast(context);
        toast.setView(customView);
        toast.setDuration(Toast.LENGTH_SHORT);

        // 获取控件的位置（相对于屏幕）
        int[] location = new int[2];
        view.getLocationOnScreen(location); // 获取控件在屏幕上的位置
        int viewX = location[0]; // 控件的X坐标
        int viewY = location[1]; // 控件的Y坐标

        WindowInsets insets = getActivity().getWindow().getDecorView().getRootWindowInsets();
        int cutoutHeight = 0;
        if (insets != null) {
            cutoutHeight = insets.getSystemWindowInsetTop(); // 获取刘海高度
        }

        // 计算Toast的偏移量
        int xOffset = 0; // 水平偏移量，与控件的X坐标对齐
        int yOffset = viewY - cutoutHeight; // 垂直偏移量，让Toast显示在控件的顶部

        // 设置Toast的位置
        toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, xOffset, yOffset);

        // 显示Toast
        toast.show();
    }

    public void showProhibitedStyleToastAboveView(View view, Context context, String message) {
        // 创建Toast
        View customView = LayoutInflater.from(context).inflate(R.layout.custom_toast_prohibited_layout, null);
        TextView toastText = customView.findViewById(R.id.toast_message);
        toastText.setText(message);

        Toast toast = new Toast(context);
        toast.setView(customView);
        toast.setDuration(Toast.LENGTH_SHORT);

        // 获取控件的位置（相对于屏幕）
        int[] location = new int[2];
        view.getLocationOnScreen(location); // 获取控件在屏幕上的位置
        int viewX = location[0]; // 控件的X坐标
        int viewY = location[1]; // 控件的Y坐标

        WindowInsets insets = getActivity().getWindow().getDecorView().getRootWindowInsets();
        int cutoutHeight = 0;
        if (insets != null) {
            cutoutHeight = insets.getSystemWindowInsetTop(); // 获取刘海高度
        }

        // 计算Toast的偏移量
        int xOffset = 0; // 水平偏移量，与控件的X坐标对齐
        int yOffset = viewY - cutoutHeight; // 垂直偏移量，让Toast显示在控件的顶部

        // 设置Toast的位置
        toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, xOffset, yOffset);

        // 显示Toast
        toast.show();
    }

    private void toast_Confirm_Style(String message) {
        View customView = LayoutInflater.from(getContext()).inflate(R.layout.custom_toast_confirm_layout, null);
        TextView toastText = customView.findViewById(R.id.toast_message);
        toastText.setText(message);

        Toast toast = new Toast(getContext());
        toast.setView(customView);
        toast.setDuration(Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.TOP, 0, 40);
        toast.show();
    }

    private void toast_Prohibited_Style(String message) {
        View customView = LayoutInflater.from(getContext()).inflate(R.layout.custom_toast_prohibited_layout, null);
        TextView toastText = customView.findViewById(R.id.toast_message);
        toastText.setText(message);

        Toast toast = new Toast(getContext());
        toast.setView(customView);
        toast.setDuration(Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.TOP, 0, 40); // 设置在屏幕顶部
        toast.show();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}
